<?php

namespace app\admin\controller;

use app\common\model\GuessModel;
use app\common\model\GuessOrderModel;
use app\common\model\QuestionModel;
use app\common\model\UserModel;
use think\Db;
use think\facade\Cache;
use think\facade\Request;

class QuestionController extends BaseController
{
    public function index()
    {
        if ($this->request->isAjax()) {
            $pageIndex = (int)$this->get('pageindex', 1);
            $pageSize = (int)$this->get('pagesize', 20);
            $model = new QuestionModel();
            if (($anchor_id = trim($this->get('anchor_id', ''))) && is_numeric($anchor_id)) {
                $model = $model->where('anchor_id', $anchor_id);
            }

            if (in_array($status = $this->get('status', ''), [1, 2, 3])) {
                $model = $model->where('status', $status);
            }

            $start_time = strtotime($this->get('start_date', ''));
            $end_time = strtotime($this->get('end_date', ''));

            if ($start_time && $end_time && ($end_time >= $start_time)) {
                $model = $model->whereBetween('create_time', [$start_time, $end_time + 86399]);
            } else if ($start_time) {
                $model = $model->whereBetween('create_time', [$start_time, time()]);
            }

            return static::bulidSuccess([
                'count' => $count = $model->count('id'),
                'list' => $model->with(['user'])
                    ->order('id', 'desc')
                    ->page($pageIndex, $pageSize)
                    ->select()->each(function ($query) {
                        if ($query->create_time) {
                            $query->create_time = date('y-m-d H:i:s', strtotime($query->create_time));
                        } else {
                            $query->create_time = '';
                        }

                        $content = trim($query->content, '|');
                        $explode = explode('|', $content);
                        array_splice($explode, $query->item_num);
                        $query->content = $explode;
                        $query->min_bet = $query->min_bet == 0 ? 0 : bcdiv($query->min_bet, '100', 2);
                    })
                    ->toArray(),
                'pageCount' => $pageCount = (int)ceil($count / $pageSize),
                'pageIndex' => $pageIndex,
                'pageSize' => $pageSize,
                'pageNav' => page_nav($pageIndex, $pageCount)
            ]);
        }

        return $this->fetch();
    }

    public function audit()
    {
        if (!($id = $this->post('id')) || !is_numeric($id)) {
            return static::bulidFail('id错误');
        }

        if (!$model = QuestionModel::where('id', $id)->find()) {
            return static::bulidFail('不存在的竞猜 请勿非法操作');
        }

        if (!in_array($status = trim($this->post('status', '')), [2, 3])) {
            return static::bulidFail();
        }

        $model->status = $status;
        $model->reason = addslashes(trim($this->post('reason', '')));
        $model->operator = $this->admin_name;

        if (!$model->save()) {
            return static::bulidFail();
        }

        $statusText =  $model->status == 2 ? '通过' : '拒绝';

        $this->addAdminLog("审核{$statusText}了一场竞猜 竞猜ID:{$model->id}");

        return static::bulidSuccess();
    }

    public function del()
    {
        if (!($id = $this->post('id')) || !is_numeric($id)) {
            return static::bulidFail('id错误');
        }

        if (!$model = QuestionModel::where('id', $id)->find()) {
            return static::bulidFail('不存在的竞猜 请勿非法操作');
        }

        if (!$model->delete()) {
            return static::bulidFail('删除失败');
        }

        $this->addAdminLog("删除了一场竞猜 竞猜ID:{$model->id}");

        return static::bulidSuccess('已删除');
    }

    public function lists()
    {
        if ($this->request->isAjax()) {
            $model = new GuessModel();
            $sql = "select sum(a.amount) as amount,count(a.id) as count from db_guess_order a left join guess.db_guess b on a.guess_id = b.id where 1=1 ";
            $sql2 = "select a.uid as uid from db_guess_order a left join guess.db_guess b on a.guess_id = b.id where 1=1 ";
            if (($anchor_id = trim($this->get('anchor_id', ''))) && is_numeric($anchor_id)) {
                $model = $model->where('anchor_id', $anchor_id);
                $sql = $sql . " and  b.anchor_id={$anchor_id}";
                $sql2 = $sql2 . " and  b.anchor_id={$anchor_id}";
            }

            if (in_array($category_id = trim($this->get('category_id', '')), [1, 2])) {
                $model = $model->where('category_id', $category_id);
                $sql = $sql . " and  b.category_id={$category_id}";
                $sql2 = $sql2 . " and  b.category_id={$category_id}";
            }

            $question = $this->get('question', []);
            $start_time = !empty($question['start_time']) ? strtotime($question['start_time']) : false;
            $end_time = !empty($question['end_time']) ? strtotime($question['end_time']) : false;

            if ($start_time && $end_time && ($end_time >= $start_time)) {
                $model = $model->whereBetween('create_time', [$question['start_time'] . ' 00:00:01', $question['end_time'] . ' 23:59:59']);
                $sql = $sql . " and  b.create_time BETWEEN '{$question['start_time']} 00:00:01' and '{$question['end_time']} 23:59:59'";
                $sql2 = $sql2 . " and  b.create_time BETWEEN '{$question['start_time']} 00:00:01' and '{$question['end_time']} 23:59:59'";
            } elseif ($start_time) {
                $model = $model->whereBetween('create_time', [$question['start_time'] . ' 00:00:01', date('Y-m-d H:i:s')]);
                $sql = $sql . " and  b.create_time BETWEEN '{$question['start_time']} 00:00:01' and '" . date('Y-m-d H:i:s') . "'";
                $sql2 = $sql2 . " and  b.create_time BETWEEN '{$question['start_time']} 00:00:01' and '" . date('Y-m-d H:i:s') . "'";
            }

            if (in_array($status = $this->get('status'), ['0', 1, 2, 3])) {
                if ($status == 0) {
                    $model = $model->where('status', 1);
                    $sql = $sql . " and  b.status=1";
                    $sql2 = $sql2 . " and  b.status=1";
                }

                if ($status == 1) {
                    $model = $model->where('pay_status', '>=', 1);
                    $sql = $sql . " and  b.pay_status>=1";
                    $sql2 = $sql2 . " and  b.pay_status>=1";
                }

                if ($status == 2) {
                    $model = $model->whereIn('status', [3, 5]);
                    $sql = $sql . " and  b.status in (3,5)";
                    $sql2 = $sql2 . " and  b.status in (3,5)";
                }

                if ($status == 3) {
                    $model = $model->where('pay_status', 0);
                    $sql = $sql . " and  b.pay_status=0";
                    $sql2 = $sql2 . " and  b.pay_status=0";
                }
            }

            $pot = $this->get('pot', []);
            if (is_numeric($pot['lowest']) && is_numeric($pot['highest']) && $pot['lowest'] > 0 && $pot['highest'] >= $pot['lowest']) {
                $model = $model->whereBetween('pot', [$pot['lowest'], $pot['highest']]);
                $sql = $sql . " and  b.pot BETWEEN {$pot['lowest']} and {$pot['highest']}";
                $sql2 = $sql2 . " and  b.pot BETWEEN {$pot['lowest']} and {$pot['highest']}";
            } else if (is_numeric($pot['lowest']) && $pot['lowest'] > 0) {
                $model = $model->where('pot', '>=', $pot['lowest']);
                $sql = $sql . " and  b.pot >= {$pot['lowest']}";
                $sql2 = $sql2 . " and  b.pot >= {$pot['lowest']}";
            }

            $sell = $this->get('sell', []);
            $start_time = !empty($sell['start_time']) ? strtotime($sell['start_time']) : false;
            $end_time = !empty($sell['end_time']) ? strtotime($sell['end_time']) : false;
            if ($start_time && $end_time && ($end_time >= $start_time)) {
                $model = $model->whereBetween('close_time', [$sell['start_time'] . ' 00:00:01', $sell['end_time'] . ' 23:59:59']);
                $sql = $sql . " and  b.close_time BETWEEN '{$sell['start_time']} 00:00:01' and '{$sell['end_time']} 23:59:59'";
                $sql2 = $sql2 . " and  b.close_time BETWEEN '{$sell['start_time']} 00:00:01' and '{$sell['end_time']} 23:59:59'";
            } elseif ($start_time) {
                $model = $model->whereBetween('close_time', [$sell['start_time'] . ' 00:00:01', date('Y-m-d H:i:s')]);
                $sql = $sql . " and  b.close_time BETWEEN '{$sell['start_time']} 00:00:01' and '" . date('Y-m-d H:i:s') . "'";
                $sql2 = $sql2 . " and  b.close_time BETWEEN '{$sell['start_time']} 00:00:01' and '" . date('Y-m-d H:i:s') . "'";
            }

            $settlement = $this->get('settlement', []);
            $start_time = !empty($settlement['start_time']) ? strtotime($settlement['start_time']) : false;
            $end_time = !empty($settlement['end_time']) ? strtotime($settlement['end_time']) : false;
            if ($start_time && $end_time && ($end_time >= $start_time)) {
                $model = $model->whereBetween('settle_time', [$settlement['start_time'] . ' 00:00:01', $settlement['end_time'] . ' 23:59:59']);
                $sql = $sql . " and  b.settle_time BETWEEN '{$settlement['start_time']} 00:00:01' and '{$settlement['end_time']} 23:59:59'";
                $sql2 = $sql2 . " and  b.settle_time BETWEEN '{$settlement['start_time']} 00:00:01' and '{$settlement['end_time']} 23:59:59'";
            } elseif ($start_time) {
                $model = $model->whereBetween('settle_time', [$settlement['start_time'] . ' 00:00:01', date('Y-m-d H:i:s')]);
                $sql = $sql . " and  b.settle_time BETWEEN '{$settlement['start_time']} 00:00:01' and '" . date('Y-m-d H:i:s') . "'";
                $sql2 = $sql2 . " and  b.settle_time BETWEEN '{$settlement['start_time']} 00:00:01' and '" . date('Y-m-d H:i:s') . "'";
            }

            $sql2 = $sql2 . ' group by a.uid';

            $countInfo = Db::query($sql);
            if (!empty($countInfo[0])) {
                $countInfo = $countInfo[0];
            }

            $countUid = Db::query($sql2);
            $countNumber = 0;
            if (!empty($countUid)) {
                $countUid = array_column($countUid, 'uid');
                $countUid = array_filter($countUid);
                $countNumber = count($countUid);
            }

            $countAmount = $countInfo['amount'] ?? 0;
            $countAmount = $countAmount == 0 ? 0 : bcdiv($countAmount, '100', 2);
            $countOrder = $countInfo['count'] ?? 0;


            return json([
                'count' => $model->count('id'),
                'list' => $model->order('id', 'desc')
                    ->page((int)$this->get('page', 1), (int)$this->get('limit', 20))
                    ->select()->each(function ($query) {
                        $query->nick_name = $query->user->nick_name ?? '';
                        $odds = json_decode($query->odds, true) ?? [];
                        foreach ($odds as &$value) {
                            $value = bcdiv($value, '100', 2);
                        }
                        $query->odds = $odds;
                        if (!$query->odds) {
                            $info = json_decode(Cache::store('redis')->get('guess:' . $query->id), true) ?? [];
                            if (!empty($info['odds_list'])) {
                                $odds_list = $info['odds_list'] ?? [];
                                foreach ($odds_list as &$value) {
                                    $value = bcdiv($value, '100', 2);
                                }
                                $query->odds = $odds_list;
                            } else {
                                $query->odds = [];
                            }
                        }
                        $content = trim($query->content, '|');
                        $explode = explode('|', $content);
                        array_splice($explode, $query->item_num);
                        $query->content_json = json_encode($explode);
                        $query->content = $explode;
                        //$query->live_title = $query->live->title ?? '';
                        $query->match_title = $query->question->match_title ?? '';
                        $query->amount = GuessOrderModel::where('guess_id', $query->id)->sum('amount');
                        $query->amount = $query->amount == 0 ? 0 : bcdiv($query->amount, '100', 2);
                        $countOrder = GuessOrderModel::where('guess_id', $query->id)->count('id');
                        $query->number = GuessOrderModel::where('guess_id', $query->id)->group('uid')->count('uid');
                        $query->number_of_bets = $query->number == 0 ? 0 : bcdiv($countOrder, $query->number, 2);
                        $query->per_capita_betting = $query->number == 0 ? 0 : bcdiv($query->amount, $query->number, 2);
                        $query->min_bet = $query->min_bet == 0 ? 0 : bcdiv($query->min_bet, '100', 2);
                    })
                    ->toArray(),
                'code' => 0,
                'totalRow' => [
                    'amount' => $countAmount,
                    'number' => $countNumber,
                    'number_of_bets' => $countNumber == 0 ? 0 : bcdiv($countOrder, $countNumber, 2),
                    'per_capita_betting' => $countNumber == 0 ? 0 : bcdiv($countAmount, $countNumber, 2)
                ],
            ]);
        }
        return $this->fetch();
    }

    public function invalid()
    {
        if (!($id = $this->post('id', '')) || !is_numeric($id)) {
            return static::bulidFail();
        }

        if (!$model = GuessModel::field('id,status')->where('id', $id)->find()) {
            return static::bulidFail('无效的竞猜 请勿非法操作');
        }

        if (!in_array($status = $this->post('status', ''), [3, 5])) {
            return static::bulidFail('无效的作废操作');
        }

        $model->status = $status;
        $model->close_time = date('Y-m-d H:i:s');
        $model->pay_status = 0;
        if (!$model->save()) {
            return static::bulidFail();
        }

        $this->addAdminLog("作废了一场竞猜 竞猜ID:{$model->id}");

        return static::bulidSuccess();
    }

    public function lottery()
    {
        if (!($id = $this->post('id', '')) || !is_numeric($id)) {
            return static::bulidFail();
        }

        if (!$model = GuessModel::field('id,status, result,content,settle_time,item_num')->where('id', $id)->find()) {
            return static::bulidFail('无效的竞猜 请勿非法操作');
        }

        if (!in_array($result = $this->post('result', ''), [1, 2, 3, 4])) {
            return static::bulidFail('无效的开奖操作');
        }

        $model->status = 4;
        $model->settle_time = date('Y-m-d H:i:s');
        $model->result = $result;
        if (!$model->save()) {
            return static::bulidFail();
        }

        $content = trim($model->content, '|');
        $explode = explode('|', $content);
        // array_splice($explode, $model->item_num);

        $this->addAdminLog("开奖了一场竞猜 竞猜ID:{$model->id} 开奖结果:{$explode[$result - 1]}");

        return static::bulidSuccess();
    }

    public function close()
    {
        if (!($id = $this->post('id', '')) || !is_numeric($id)) {
            return static::bulidFail();
        }

        if (!$model = GuessModel::field('id,status')->where('id', $id)->find()) {
            return static::bulidFail('无效的竞猜 请勿非法操作');
        }

        if ($model->status == 2) {
            return static::bulidSuccess([], '已封盘');
        }

        $model->status = 2;
        $model->close_time = date('Y-m-d H:i:s');
        if (!$model->save()) {
            return static::bulidFail();
        }

        $this->addAdminLog("关闭了一场竞猜 竞猜ID:{$model->id}");

        return static::bulidSuccess();
    }

    public function info()
    {
        if (!($id = trim($this->get('id', ''))) || !is_numeric($id)) {
            return static::bulidFail('竞猜ID错误');
        }

        if (!$model = GuessModel::field('*')->where('id', $id)->find()) {
            return static::bulidFail('不存在的竞猜');
        }

        if ($this->request->isAjax()) {
            $model = GuessOrderModel::field('id,uid,guess_item,amount,status,profit,create_time');
            $model = $model->where('guess_id', $id);
            if ($account = trim($this->get('account', ''))) {
                if ($user = UserModel::field('id')->where('account', $account)->find()) {
                    $model = $model->where('uid', $user->id);
                } else {
                    return json([
                        'count' => 0,
                        'list' => [],
                        'code' => 0,
                    ]);
                }
            }
            return json([
                'count' => $model->count('id'),
                'list' => $model->order('id', 'desc')
                    ->page((int)$this->get('page', 1), (int)$this->get('limit', 20))
                    ->select()->each(function ($query) {
                        $query->account = $query->user->account ? mobileHide($query->user->account, $this->userinfo->roleid) : '';
                        $query->amount = $query->amount == 0 ? 0 : bcdiv($query->amount, '100', 2);
                        $query->profit = $query->profit == 0 ? 0 : bcdiv($query->profit, '100', 2);
                    })
                    ->toArray(),
                'code' => 0,
            ]);
        }

        $explode = explode('|', trim($model->content, '|'));
        array_splice($explode, $model->item_num);

        return $this->assign(['model' => $model, 'content_json' => json_encode($explode)])->fetch();
    }

    public function rank()
    {
        return $this->fetch();
    }

    public function ajax_rank()
    {
        $params = Request::param();
        $where = [];
        if (isset($params['date']) && $params['date'] != "") {
            $where[] = ['create_time', '>', $params['date']];
            $where[] = ['create_time', '<', $params['date'] . " 23:59:59"];
        } else {
            $where[] = ['create_time', '>', date("Y-m-d 00:00:00", time())];
            $where[] = ['create_time', '<', date("Y-m-d 23:59:59", time())];
        }

        $count = GuessModel::where($where)->count();
        $list = GuessModel::where($where)->page((int)$this->get('page', 1), (int)$this->get('limit', 20))->select();
        if (count($list) == 0) {
            return self::bulidFail("未查询到相关数据");
        }

        foreach ($list as $key => $value) {
            $user = UserModel::where("id", $value['anchor_id'])->find();
            $list[$key]['anchor_name'] = $user['nick_name'];
            $list[$key]['joins'] = GuessOrderModel::where("guess_id", $value['id'])->count();
        }

        return json(["code" => 0, "msg" => "", "data" => $list, "count" => $count]);
    }

    public function user()
    {
        return $this->fetch();
    }

    public function ajax_user()
    {
        $params = Request::param();
        $where = [];
        if (isset($params['date']) && $params['date'] != "") {
            $where[] = ['create_time', '>', $params['date']];
        }

        if (isset($params['end_date']) && $params['end_date'] != "") {
            $where[] = ['create_time', '<', $params['end_date'] . " 23:59:59"];
        }

        if (!isset($params['date']) && !isset($params['end_date'])) {
            $where[] = ['create_time', '>', date("Y-m-d 00:00:00", time())];
            $where[] = ['create_time', '<', date("Y-m-d 23:59:59", time())];
        }


        $win[] = ['status', 'in', '3,2'];

        $count = GuessOrderModel::where($where)->group("uid")->count();
        $list = GuessOrderModel::where($where)->where($win)->field("uid, count(*) as times, sum(amount) as amount, sum(profit) as profit")->page((int)$this->get('page', 1), (int)$this->get('limit', 20))->group("uid")->order("times desc")->select();
        if (count($list) == 0) {
            return self::bulidFail("未查询到相关数据");
        }

        foreach ($list as $key => $value) {
            $user = UserModel::where("id", $value['uid'])->find();
            $list[$key]['name'] = $user['nick_name'];
            $list[$key]['sum'] = $value['profit'] - $value['amount'];
            $list[$key]['times'] = GuessOrderModel::where($where)->where("uid", $value['uid'])->where($win)->group("guess_id")->count();
            $list[$key]['count'] = GuessOrderModel::where($where)->where("uid", $value['uid'])->group("guess_id")->count();
            $list[$key]['rotia'] = intval($value['times'] / $value['count'] * 100) . "%";
        }

        return json(["code" => 0, "msg" => "", "data" => self::bubble_sort($list), "count" => $count]);
    }

    private static function bubble_sort($data)
    {
        for ($i = 0; $i < count($data); $i++) {
            // 第二层将从键为$i的地方循环到数组最后
            for ($j = $i + 1; $j < count($data); $j++) {
                // 比较数组中相邻两个值的大小
                if ($data[$i]['count'] < $data[$j]['count']) {
                    $tmp            = $data[$i]; // 这里的tmp是临时变量
                    $data[$i] = $data[$j]; // 第一次更换位置
                    $data[$j] = $tmp;            // 完成位置互换
                }
            }
        }

        return $data;
    }
}
